

#import "ASGChooseCityController.h"
#import "ASGCityGroupCell.h"
#import "ASGCityHeaderView.h"
#import "LocationHelper.h"
#import "ISGLocationInfoModel.h"
#import "ASGSearchBar.h"
//#import "UIViewExt.h"
#import "UIView+ZLExtension.h"
#import <CoreLocation/CoreLocation.h>
#import "UIColor+Hex.h"
#define MAX_COMMON_CITY_NUMBER          3

@interface ASGChooseCityController () <UITableViewDelegate,UITableViewDataSource,ASGCityGroupCellDelegate,UISearchBarDelegate,CLLocationManagerDelegate,ISGLocationHelperDelegate>
{
    NSString *_locationPlace;
    NSString *_locationCity;
}
@property (nonatomic, strong) NSMutableArray *recordCityData;//记录所有城市信息，用于搜索
@property (nonatomic, strong) NSMutableArray *localCityData;//定位城市
@property (nonatomic, strong) NSMutableArray *hotCityData;//热门城市
@property (nonatomic, strong) NSMutableArray *commonCityData;//最近访问城市
@property (nonatomic, strong) NSMutableArray *arraySection;//右边的几个选项--------------
@property (nonatomic, assign) BOOL isSearch;//是否是search状态
@property (nonatomic, strong) NSMutableArray *searchCities;//搜索城市列表
@property (nonatomic, strong) LocationHelper *locationHelper;
@property (nonatomic, strong) UITableView    *tableView;
@property (nonatomic, strong) NSMutableArray *commonCitys;//常用城市id数组
@property (nonatomic, strong) NSMutableArray *cityDatas;//城市数据

@end

NSString *const cityHeaderView = @"CityHeaderView";
NSString *const cityGroupCell = @"CityGroupCell";
NSString *const cityCell = @"CityCell";

@implementation ASGChooseCityController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self localDataInitialize];
    [self navigationBarItemsLoad];
    [self subviewsLoad];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self loadHotCityData];
}

#pragma mark - UI
- (void)localDataInitialize{
    self.searchCities = [NSMutableArray new];//搜索城市列表
    self.recordCityData = [NSMutableArray new];//所有城市信息----
    self.arraySection = [[NSMutableArray alloc] initWithObjects:UITableViewIndexSearch, @"定位", @"城市", @"历史",@"热门", nil];
    NSArray *array = [[NSUserDefaults standardUserDefaults] objectForKey:COMMON_CITY_DATA_KEY];
    self.commonCitys = (array == nil ? [NSMutableArray new] : [[NSMutableArray alloc] initWithArray:array copyItems:YES]);//最近访问城市
}

- (void)navigationBarItemsLoad {
    self.navigationItem.title = @"选择城市";
    UIBarButtonItem *cancelBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"hp_chooseCityBack"] style:UIBarButtonItemStylePlain target:self action:@selector(cancelButtonDown:)];
    cancelBarButton.tintColor = [UIColor whiteColor];
    [self.navigationItem setLeftBarButtonItem:cancelBarButton];
}

- (void)subviewsLoad {
    _locationHelper = [[LocationHelper alloc] init];
    _locationHelper.delegate = self;
    [_locationHelper startLocation];
    
    [self loadSearchBar];
    [self loadTableView];
}

- (void)loadSearchBar {
    UIView *searchBarView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Width, 44)];
    searchBarView.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.0];
    [self.view addSubview:searchBarView];
    
    ASGSearchBar *searchBar = [[ASGSearchBar alloc]initWithFrame:CGRectMake(15, 0, Width - 30, searchBarView.zl_height)];
    searchBar.placeholder  = @"输入城市名称";
    searchBar.delegate = self;
    [searchBarView addSubview:searchBar];
}

- (void)loadTableView {
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    tableView.backgroundColor = [UIColor whiteColor];
    tableView.separatorColor = cCommonLineColor;
    tableView.delegate = self;
    tableView.dataSource = self;
    [self.view addSubview:tableView];
    [tableView makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.offset(0);
        make.top.offset(44);
    }];
    
    [tableView setSectionIndexBackgroundColor:[UIColor clearColor]];
    [tableView setSectionIndexColor:cCommonRedColor];
    [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cityCell];
    [tableView registerClass:[ASGCityGroupCell class] forCellReuseIdentifier:cityGroupCell];
    [tableView registerClass:[ASGCityHeaderView class] forHeaderFooterViewReuseIdentifier:cityHeaderView];
    self.tableView = tableView;
}

#pragma mark - network
- (void)loadHotCityData {
//    @weakify(self);
//    [ASGNetWorkEngine requestWithURL:sServiceUrlAllHotCity sessionID:NO params:nil completeBlock:^(NSDictionary *result) {
//        @strongify(self);
//        [self.tableView.mj_footer endRefreshing];
//
//        NSDictionary *contentDic = [result objectForKey:@"contents"];
//        NSArray *job_list = [contentDic objectForKey:@"rows"];
//        for (NSDictionary *jobs in job_list) {
//            ASGCityInfo *city = [[ASGCityInfo alloc] init];
//            city.cityID = [jobs objectForKey:@"id"];
//            city.cityName = [jobs objectForKey:@"areaName"];
//            [self.hotCityData addObject:city];
//        }
//        
//        [self.tableView reloadData];
//        
//    } failedBlock:^(NSError *error) {
//        @strongify(self);
//        [self.tableView.mj_footer endRefreshing];
//    }];
}


#pragma mark -ISGLocationHelperDelegate
- (void)locationHelper:(LocationHelper *)helper successWithModel:(ISGLocationInfoModel *)model {
    
    NSString *city = model.city;
    
    if (self.localCityData.count <= 0) {
        ASGCityInfo *temp = [[ASGCityInfo alloc] init];
        temp.cityName = city;
        temp.shortName = city;
        [self.localCityData addObject:temp];
    }
    
    _locationPlace = model.address;
    _locationCity = city;
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    [userDefault setObject:model.latitude forKey:@"currentlatitude"];
    [userDefault setObject:model.longitude forKey:@"currentlongitude"];
    [userDefault synchronize];
    
    [self.tableView reloadData];
}

#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.isSearch) {
        return 1;
    }
    return self.cityDatas.count + 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (self.isSearch) {
        return self.searchCities.count;
    }
    if (section < 4) {
        return 1;
    }
    GYZCityGroup *group = [self.cityDatas objectAtIndex:section - 4];
    return group.arrayCitys.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.isSearch) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cityCell];
        ASGCityInfo *city =  [self.searchCities objectAtIndex:indexPath.row];
        [cell.textLabel setText:city.cityName];
        return cell;
    }
    
    if (indexPath.section < 4) {
        ASGCityGroupCell *cell = [tableView dequeueReusableCellWithIdentifier:cityGroupCell];
        if (indexPath.section == 0) {
            cell.titleLabel.text = @"当前位置";
            [cell setCurrentPalce:_locationPlace];
        } else if (indexPath.section == 1) {
            cell.titleLabel.text = @"当前城市";
            [cell setCurrentPalce:_locationCity];
        } else if (indexPath.section == 2) {
            cell.titleLabel.text = @"历史访问城市";
            [cell setCityArray:self.commonCityData];
        } else if (indexPath.section == 3)  {
            cell.titleLabel.text = @"热门城市";
            [cell setCityArray:self.hotCityData];
        }
        [cell setDelegate:self];
        return cell;
    }
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cityCell];
    GYZCityGroup *group = [self.cityDatas objectAtIndex:indexPath.section - 4];
    ASGCityInfo *city =  [group.arrayCitys objectAtIndex:indexPath.row];
    [cell.textLabel setText:city.cityName];
    [cell.textLabel setFont:[UIFont systemFontOfSize:15.0]];
    
    return cell;
}

#pragma mark UITableViewDelegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section < 4) {
        return nil;
    }
    ASGCityHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:cityHeaderView];
    NSString *title = [_arraySection objectAtIndex:section + 1];
    headerView.titleLabel.text = title;
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isSearch) {
        return 44.0f;
    }
    if (indexPath.section == 2) {
        return [ASGCityGroupCell getCellHeightOfCityArray:self.commonCityData];
    }
    if (indexPath.section == 3) {
        return [ASGCityGroupCell getCellHeightOfCityArray:self.hotCityData];
    }
    return 44.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section < 4) {
        return 0.0f;
    }
    return 23.5f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BaseViewController *c = [BaseViewController new];
    c.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController pushViewController:c animated:YES];
    return;
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ASGCityInfo *city = nil;
    if (self.isSearch) {
        city =  [self.searchCities objectAtIndex:indexPath.row];
    } else {
        if (indexPath.section < 4) {
            if (indexPath.section == 0 || indexPath.section == 1) {
                if (self.localCityData.count == 0) {
                    // 重新定位
                    [_locationHelper startLocation];
                } else if (self.localCityData.count > 0) {
                    [self didSelctedCity:self.localCityData.firstObject];
                }
            }
            return;
        }
        GYZCityGroup *group = [self.cityDatas objectAtIndex:indexPath.section - 4];
        city =  [group.arrayCitys objectAtIndex:indexPath.row];
    }
    
    [self didSelctedCity:city];
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (self.isSearch) {
        return nil;
    }
    return self.arraySection;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    if (index == 0) {
        return -1;
    }
    return index - 1;
}

#pragma mark searchBarDelegete
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {

}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [self.searchCities removeAllObjects];
    
    if (searchText.length == 0) {
        self.isSearch = NO;
    } else {
        self.isSearch = YES;
        for (ASGCityInfo *city in self.recordCityData) {
            NSRange chinese = [city.cityName rangeOfString:searchText options:NSCaseInsensitiveSearch];
            NSRange  letters = [city.pinyin rangeOfString:searchText options:NSCaseInsensitiveSearch];
            NSRange  initials = [city.initials rangeOfString:searchText options:NSCaseInsensitiveSearch];
            
            if (chinese.location != NSNotFound || letters.location != NSNotFound || initials.location != NSNotFound) {
                [self.searchCities addObject:city];
            }
        }
    }
    [self.tableView reloadData];
}

//添加搜索事件：
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [searchBar setShowsCancelButton:NO animated:YES];
    searchBar.text = @"";
    [searchBar resignFirstResponder];
    self.isSearch = NO;
    [self.tableView reloadData];
}

#pragma mark - GYZCityGroupCellDelegate
- (void)cityGroupCellDidSelectCity:(ASGCityInfo *)city
{
    [self didSelctedCity:city];
}

#pragma mark - Event Response
- (void)cancelButtonDown:(UIBarButtonItem *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - private methods

- (void)didSelctedCity:(ASGCityInfo *)city
{
    for (NSString *str in self.commonCitys) {
        if ([city.cityName isEqualToString:str]) {
            [self.commonCitys removeObject:str];
            break;
        }
    }
    [self.commonCitys insertObject:city.cityName atIndex:0];
    
    if (self.commonCitys.count > MAX_COMMON_CITY_NUMBER) {
        [self.commonCitys removeLastObject];
    }
    
    NSString *provinceString = [self getProvinceString:city.cityName];
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    [userDefault setObject:provinceString forKey:@"currentProvince"];
    [userDefault setValue:self.commonCitys forKey:COMMON_CITY_DATA_KEY];
    [userDefault setObject:city.cityName forKey:@"currentCity"];
    [userDefault synchronize];
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSString *)getProvinceString:(NSString *)city{
    NSData *provinceData = [[NSData alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"province" ofType:@"txt"]];
    NSArray *provinceArr = [NSJSONSerialization JSONObjectWithData:provinceData options:NSJSONReadingMutableContainers error:nil];
    for (NSDictionary *provinceDic in provinceArr) {
        NSArray *cityArr = provinceDic[@"child"];
        for (NSDictionary *cityDic in cityArr) {
            if ([cityDic[@"name"] isEqualToString:city]) {
                return provinceDic[@"name"];
            }
        }
    }
    return @"";
}

#pragma mark - getters and setters
// MARK: - 所有城市的数据------------------
-(NSMutableArray *)cityDatas {
    if (_cityDatas == nil) {
//        province.txt来获取省份信息的-----
        NSArray *array = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"CityData" ofType:@"plist"]];
        _cityDatas = [[NSMutableArray alloc] init];
        for (NSDictionary *groupDic in array) {
            GYZCityGroup *group = [[GYZCityGroup alloc] init];
            group.groupName = [groupDic objectForKey:@"initial"];
            for (NSDictionary *dic in [groupDic objectForKey:@"citys"]) {
                ASGCityInfo *city = [[ASGCityInfo alloc] init];
                city.cityID = [dic objectForKey:@"city_key"];
                city.cityName = [dic objectForKey:@"city_name"];
                city.shortName = [dic objectForKey:@"short_name"];
                city.pinyin = [dic objectForKey:@"pinyin"];
                city.initials = [dic objectForKey:@"initials"];
                [group.arrayCitys addObject:city];
                [self.recordCityData addObject:city];
            }
            [self.arraySection addObject:group.groupName];
            [_cityDatas addObject:group];
        }
    }
    return _cityDatas;
}

// MARK: - 定位城市数据-----
- (NSMutableArray *)localCityData
{
    if (_localCityData == nil) {
        _localCityData = [[NSMutableArray alloc] init];
    }
    return _localCityData;
}

// MARK: - 热门城市数据---------
- (NSMutableArray *)hotCityData
{
    if (_hotCityData == nil) {
        _hotCityData = [[NSMutableArray alloc] init];
    }
    return _hotCityData;
}

- (NSMutableArray *)commonCityData
{
    if (_commonCityData == nil) {
        _commonCityData = [[NSMutableArray alloc] init];
        for (NSString *str in self.commonCitys) {
            ASGCityInfo *city = nil;
            for (ASGCityInfo *item in self.recordCityData) {
                if ([item.cityName isEqualToString:str]) {
                    city = item;
                    break;
                }
            }
            if (city == nil) {
                TBLog(@"Not Found City: %@", str);
            } else {
                [_commonCityData addObject:city];
            }
        }
    }
    return _commonCityData;
}

@end
